import { API_BASE_URL } from '@/config/env';

export interface ImUser {
  user_id: string;
  user_name?: string;
  mobile?: string;
  create_time?: number;
  update_time?: number;
  version?: number;
  del_flag?: number;
}

export interface ImUserData {
  user_id: string;
  name?: string;
  avatar?: string;
  gender?: number;
  birthday?: string;
  location?: string;
  self_signature?: string;
  friend_allow_type: number;
  forbidden_flag: number;
  disable_add_friend: number;
  silent_flag: number;
  user_type: number;
  del_flag: number;
  extra?: string;
  create_time?: number;
  update_time?: number;
  version?: number;
}

export interface CreateImUserRequest {
  user_id: string;
  user_name: string;
  password: string;
  mobile?: string;
}

export interface LoginRequest {
  user_name: string;
  password: string;
}

export interface LoginResponse {
  user: ImUser;
  token: string;
}

export const createImUser = async (req: CreateImUserRequest): Promise<ImUser> => {
  const response = await fetch(`${API_BASE_URL}/api/im/users`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '创建用户失败' }));
    throw new Error(error.message || '创建用户失败');
  }

  return response.json();
};

export const loginImUser = async (user_name: string, password: string): Promise<LoginResponse> => {
  const response = await fetch(`${API_BASE_URL}/api/im/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ user_name, password }),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '登录失败' }));
    throw new Error(error.message || '登录失败');
  }

  const data = await response.json();
  localStorage.setItem('token', data.token);
  localStorage.setItem('imUser', JSON.stringify(data.user));
  localStorage.setItem('imUserId', data.user.user_id);
  return data;
};

export const getImUser = async (user_id: string): Promise<ImUser> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${API_BASE_URL}/api/im/users/${encodeURIComponent(user_id)}`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取用户失败' }));
    throw new Error(error.message || '获取用户失败');
  }

  return response.json();
};

export const getUserData = async (user_id: string): Promise<ImUserData> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${API_BASE_URL}/api/im/users/${encodeURIComponent(user_id)}/data`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '获取用户数据失败' }));
    throw new Error(error.message || '获取用户数据失败');
  }

  return response.json();
};

export const upsertUserData = async (user_data: ImUserData): Promise<void> => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${API_BASE_URL}/api/im/users/${encodeURIComponent(user_data.user_id)}/data`, {
    method: 'PUT',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(user_data),
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: '更新用户数据失败' }));
    throw new Error(error.message || '更新用户数据失败');
  }
};

